package com.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author kangshuai
 */
@Slf4j
@Component
public class BrushStrokeFilter implements GlobalFilter, Ordered {

    /**
     * 请求记录表
     */
    private static ConcurrentHashMap<String, CopyOnWriteArrayList<Long>> ipRequestMap = new ConcurrentHashMap<>();
    @Value("${brushStroke.time}")
    public int time;
    @Value("${brushStroke.number}")
    public int number;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 思路：获取客户端ip，记录请求时间，判断最近time分钟内，请求次数是否在number以内，在的话就放⾏
        // 从上下⽂中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址
        String path = request.getPath().toString();
        if (path.startsWith("/api")) {
            // 从request对象中获取客户端ip
            String clientIp = request.getRemoteAddress().getHostString();

            //判断方法是否存在于map中
            if (!ipRequestMap.containsKey(clientIp)) {
                CopyOnWriteArrayList<Long> list = new CopyOnWriteArrayList<Long>();
                list.add(System.currentTimeMillis());
                ipRequestMap.put(clientIp, list);
            } else {
                //判断ipRequestMap中得请求次数是否超了
                CopyOnWriteArrayList<Long> list = ipRequestMap.get(clientIp);
                //遍历 list
                Iterator<Long> iterator = list.iterator();
                //请求总数
                int requestCount = 0;
                //当前时间
                Long now = System.currentTimeMillis();
                while (iterator.hasNext()) {
                    Long requestTime = iterator.next();
                    //超过了指定时间内得请求删除
                    if (now - requestTime > time * 60 * 1000) {
                        list.remove(requestTime);
                    } else {
                        requestCount++;
                    }
                }
                //判断请求次数是否超过阈值
                if (requestCount > number) {
                    // 决绝访问，返回// 状态码
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    log.error("=====>IP:" + clientIp + " 暴刷");
                    String data = "错误码：303，错误信息：您频繁进⾏注册，请求已被拒绝!";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                } else {
                    ipRequestMap.get(clientIp).add(System.currentTimeMillis());
                }
            }
        }

        // 合法请求，放⾏，执⾏后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

